package demo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import util.Configuration;
import util.FileNameUtil;
import util.po.ConfigPO;

/**
 * Socket 服务端
 * 
 * @author sundy.hu
 * @version 1.0
 * @date 2012-11-28
 * 
 */
public class Server implements Runnable {

	// 服务端口
	private int port;
	// Socket服务端
	private ServerSocket serverSocket;
	// 文件接收存放路径
	private String path;

	private Logger log = Logger.getLogger(Server.class.getName());

	private ConfigPO config = new Configuration().configure();

	// 设置路径
	public void setPath(String path) {
		this.path = path;
	}

	// 设置端口号
	public Server() {
		this.port = config.getServerSocketPort();
		this.path = config.getReceivePath();
		log.info("getter port " + String.valueOf(port));
		log.setLevel(Level.INFO);
	}

	@Override
	public void run() {
		try {
			serverSocket = new ServerSocket(port);
			log.info("server startup at " + port);
			while (true) {
				Socket client = serverSocket.accept();
				receive(client);
			}
		} catch (IOException ex) {
			log.warning(ex.getLocalizedMessage());
			ex.printStackTrace();
		}

	}

	public static String data = "";

	// 接收文件
	private void receive(Socket client) {
		if (null != client) {
			try {
				int len = 0;
				BufferedInputStream input = new BufferedInputStream(
						client.getInputStream());
				client.setReceiveBufferSize(config.getReceiveBufferSize() * 10);
				String fileName = path + File.separator
						+ FileNameUtil.getFileName()
						+ config.getReceiveExtName();
				OutputStream output = new FileOutputStream(fileName);
				DataOutputStream dos = new DataOutputStream(
						new BufferedOutputStream(output));
				DataInputStream dis = new DataInputStream(input);
				// byte[] b = new byte[1024];
				int i = 0;
				while ((len = dis.read()) != -1) {
					dos.write((char) len);
					++i;
					if (len % client.getReceiveBufferSize() == 0) {
						dos.flush();
					}
				}
				System.out.println("total receive " + i);
				input.close();
				dis.close();
				dos.flush();
				dos.close();

				output.flush();
				output.close();
				client.close();
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				log.info(sdf.format(new Date()) + fileName
						+ " receive successful");
				System.out.println();
			} catch (IOException ex) {
				log.warning(ex.getLocalizedMessage());
				ex.printStackTrace();
			}
		}
	}

}
